﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Collections;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System;
using System.Collections;
using System.Text;
using System.Text.RegularExpressions;
using System.Security.Cryptography;
using System.Configuration;
using System.Data;
using System.Management;
using System.Data.SqlClient;

using System.Runtime.InteropServices;
using DotNetNuke.Common.Utilities;
using System;
using System.Data;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Web.UI;
using System.Web.UI.WebControls;

using DotNetNuke;
using DotNetNuke.Common;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Modules.Actions;
using DotNetNuke.Security;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Localization;
using System.Globalization;
using System.Configuration;
using System;
using System.Web.UI.WebControls;
using DevExpress.Web.ASPxGridView;
using DevExpress.Web.ASPxDataView;
using DevExpress.Web.ASPxEditors;
using DevExpress.Web;
using System.Web.UI;
using DevExpress.Web.ASPxClasses.Internal;
using DevExpress.Web.ASPxGridLookup;
using System.IO;


/// <summary>
/// Summary description for Customer
/// </summary>
namespace Triax.Modules.Department
{
    public class CommonLib
    {
        //%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -i //Khởi động iis bằng commandline, fix lỗi HTTP Error 500.21 - Internal Server Error

        private static string _ConnectString = "";
        public static string ConnectString
        {
            get
            {
                _ConnectString = ConfigurationManager.AppSettings["SiteSqlServer"];
                return _ConnectString;
            }
        }

        public static string _NumbericFormatString = "";
        public static string NumbericFormatString
        {
            get
            {
                return "### ### ### ### ###.#";
            }
            set
            {
                _NumbericFormatString = value;
            }
        }

        public static string _IntegerFormatString = "";
        public static string IntegerFormatString
        {
            get
            {
                return "### ### ### ### ###";
            }
            set
            {
                _IntegerFormatString = value;
            }
        }

        //method tăng số cho các bảng, dạng số [Mã loại][Năm]-[THáng]-[Ngày]-[0000000] VD BN20170227-0088
        public static string TaoTienToMaSoTheoChuan(string kiHieuPhieu)
        {
            DateTime systemDate = GetSystemDateTime();
            string day = FormatSoTheoDoDai(systemDate.Day.ToString(), 2);
            string month = FormatSoTheoDoDai(systemDate.Month.ToString(), 2);

            string result = kiHieuPhieu + GetSystemDateTime().Year.ToString() + month + day + "-";
            return result;
        }
        public static string GetMaSoMacDinhByTable(string tableName, string columnName, string prefix, int doDaiSo)
        {
            int noDigits = doDaiSo;
            SqlConnection con = new SqlConnection(ConnectString);
            try
            {
                con.Open();
                SqlCommand cmd = con.CreateCommand();
                SqlDataReader rd = null;

                string pattern = prefix;
                if (prefix.Contains("Ă"))
                    pattern = prefix.Replace("Ă", "%");
                else if (prefix.Contains("Â"))
                    pattern = prefix.Replace("Â", "%");
                else if (prefix.Contains("Đ"))
                    pattern = prefix.Replace("Đ", "%");
                else if (prefix.Contains("Ê"))
                    pattern = prefix.Replace("Ê", "%");
                else if (prefix.Contains("Ô"))
                    pattern = prefix.Replace("Ô", "%");
                else if (prefix.Contains("Ơ"))
                    pattern = prefix.Replace("Ơ", "%");
                else if (prefix.Contains("Ư"))
                    pattern = prefix.Replace("Ư", "%");

                for (int i = 0; i < noDigits; i++)
                    pattern += "[0-9]";

                cmd.CommandText = string.Format("SELECT TOP 1 {1} FROM [{0}] \n" +
                                                "WHERE {1} LIKE N'{2}' ORDER BY {1} DESC",
                                                tableName, columnName, pattern);

                Int64 maxOldID = 0;
                rd = cmd.ExecuteReader();
                if (rd.Read())
                {
                    string maxOldSoHieu = (string)rd[columnName];
                    if (maxOldSoHieu.StartsWith(prefix)) maxOldSoHieu = maxOldSoHieu.Substring(prefix.Length);
                    if (maxOldSoHieu.Length > noDigits) maxOldSoHieu = maxOldSoHieu.Substring(maxOldSoHieu.Length - noDigits);

                    Regex regex = new Regex(string.Format(@"(?<=.*)(\d)+"));
                    Match match = regex.Match(maxOldSoHieu);
                    try
                    {
                        maxOldID = Int64.Parse(match.Value);
                    }
                    catch (Exception ex)
                    {
                    }
                }
                rd.Close();

                while (true)
                {
                    maxOldID++;
                    string strDigits = maxOldID.ToString();
                    int digitsLength = strDigits.Length;
                    for (int i = digitsLength; i < noDigits; i++)
                    {
                        strDigits = "0" + strDigits;
                    }

                    string soChungTu = "";

                    soChungTu = string.Format("{0}{1}", prefix, strDigits);

                    cmd.CommandText = string.Format("SELECT {0} FROM [{1}] WHERE {0} = N'{2}' ",
                                                        columnName, tableName, pattern);
                    rd = cmd.ExecuteReader();

                    return soChungTu;
                    rd.Close();
                }
                return "";
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                con.Close();
            }
        }

        public static string FormatSoTheoDoDai(string so, int doDai)
        {
            try
            {
                string str = so;
                int digitsLength = so.Length;
                for (int i = digitsLength; i < doDai; i++)
                {
                    str = "0" + str;
                }

                return str;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public static int PageSize_DoDaiTrang = 20;

        //Lấy số ngày trong năm
        public static string GetSystemDateTimeDayOfYear()
        {
            SqlConnection con = new SqlConnection(ConnectString);
            try
            {
                con.Open();
                SqlCommand cmd = con.CreateCommand();
                return GetSystemDateTimeDayOfYear(cmd);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                con.Close();
            }
        }
        public static string GetSystemDateTimeDayOfYear(SqlCommand cmd)
        {
            try
            {
                cmd.CommandText = "SELECT GETDATE()";
                DateTime retDate = (DateTime)cmd.ExecuteScalar();

                int dayOfYear = retDate.DayOfYear;
                string result = dayOfYear.ToString();
                int noDigits = 3; //1 năm có 365 --> cần format đến hàng trăm


                for (int i = result.Length; i < noDigits; i++)
                {
                    result = "0" + result;
                }

                return result;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        //Method ép kiểu decimal cho các object, nếu k ép được trả về 0 để tránh lỗi null
        public static decimal ConvertToDecimal(object obj)
        {
            try
            {
                decimal result = Convert.ToDecimal(obj);
                return result;
            }
            catch (Exception ex)
            {
                return 0;
            }
        }
        public static decimal ConvertToDecimal(string obj)
        {
            try
            {
                decimal result = Convert.ToDecimal(obj);
                return result;
            }
            catch (Exception ex)
            {
                return 0;
            }
        }

        public static string ExtractToArrayNumber(string stringSource)
        {
            Regex myRegex = new Regex(@"\D");
            string chuoiSo = myRegex.Replace(stringSource, "");

            return chuoiSo;
        }
        public static bool StartWithSoMay(string stringSource)
        {
            SqlConnection con = new SqlConnection(ConnectString);

            try
            {
                con.Open();
                SqlCommand cmd = con.CreateCommand();
                SqlDataReader rd = null;
                string maybeSoMay = "";

                //TH1: K convert được thành kiểu int --> có chữ cái
                if (stringSource.Length >= 2) maybeSoMay = stringSource.Substring(0, 2);
                try
                {
                    int test = Convert.ToInt32(maybeSoMay.ToString());
                }
                catch (Exception ex)
                {
                    return false; //Không phải số máy vì không ép kiểu được
                }
                //Nếu convert được thì xét tiếp
                //Cẩn thận trường hợp ExtractToArrayNumber xong thì H1 -> 1 , tưởng nhầm là số máy
                maybeSoMay = ExtractToArrayNumber(maybeSoMay);  //Loại bỏ các chữ không phải là chữ số. Cho ra chuỗi ký tự chỉ chứa các chữ số (tối đa 2 chữ số)
                if (maybeSoMay != "")
                {
                    cmd.CommandText = string.Format("SELECT TOP 1 * FROM MayTinh WHERE OrderNumber = {0}", maybeSoMay);
                    rd = cmd.ExecuteReader();
                }
                else return false;

                if (rd != null && rd.Read())
                    return true;
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                con.Close();
            }
        }

        public static string ReplaceAllSpecialCharacter(string textSource, string charReplaceTo)
        {
            return Regex.Replace(textSource, @"[^\w\.-]", charReplaceTo);
        }

        public static string TangSoChungTuTuDong(string oldSoChungTu, int soLuyTien)
        {
            try
            {
                string newSoChungTu = "", newSuffix = "";
                newSuffix = string.Format("{0}", int.Parse(ExtractToArrayNumber(oldSoChungTu)) + soLuyTien);
                //Đưa suffix mới vào 
                newSoChungTu = string.Format("{0}{1}", oldSoChungTu.Substring(0, oldSoChungTu.Length - newSuffix.Length), newSuffix);

                return newSoChungTu;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        public static string GetSoHieuMacDinh(string tableName, string fieldName, string prefix, int noDigits)
        {
            try
            {
                string soChungTu = "";
                if (fieldName == "") fieldName = "So";
                using (SqlConnection con = new SqlConnection(ConnectString))
                {
                    try
                    {
                        con.Open();
                        string strSql = string.Format("SELECT TOP 1 * FROM {0} ORDER BY {0}ID DESC", tableName);
                        SqlCommand cmd = new SqlCommand(strSql, con);
                        SqlDataReader rd = cmd.ExecuteReader();
                        if (rd.Read())
                        {
                            string maxOldSoHieu = (string)rd[fieldName];
                            Regex regex = new Regex(string.Format(@"(?<=.*?)(\d)+", prefix));
                            Match match = regex.Match(maxOldSoHieu);
                            int maxOldID = 0;
                            try
                            {
                                maxOldID = int.Parse(match.Value);
                            }
                            catch
                            {
                            }
                            string digits = (++maxOldID).ToString();
                            int digitsLength = digits.Length;
                            for (int i = digitsLength; i < noDigits; i++)
                            {
                                digits = "0" + digits;
                            }
                            soChungTu = string.Format("{0}{1}", prefix, digits);
                            //while (existed)
                            //{
                            //    soChungTu = string.Format("{0}{1}", suffix, digits);
                            //    cmd = new SqlCommand("SELECT COUNT(*) FROM 
                            //}
                        }
                        else
                        {
                            string digits = "1";
                            int digitsLength = digits.Length;
                            for (int i = digitsLength; i < noDigits; i++)
                            {
                                digits = "0" + digits;
                            }
                            soChungTu = string.Format("{0}{1}", prefix, digits);
                        }
                    }
                    catch (Exception ex)
                    {
                    }
                }
                return soChungTu;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        public static string GetSoHieuMacDinh(string tableName, string fieldName, string prefix, int noDigits, bool tangTheoTungSoMay)
        {
            try
            {
                string soChungTu = "";
                if (fieldName == "") fieldName = "So";
                using (SqlConnection con = new SqlConnection(ConnectString))
                {
                    try
                    {
                        con.Open();

                        string strSql = string.Format("SELECT TOP 1 * FROM {0} ORDER BY {0}ID DESC", tableName);
                        SqlCommand cmd = new SqlCommand(strSql, con);
                        SqlDataReader rd = cmd.ExecuteReader();
                        if (rd.Read())
                        {
                            string maxOldSoHieu = (string)rd[fieldName];
                            Regex regex = new Regex(string.Format(@"(?<=.*?)(\d)+", prefix));
                            Match match = regex.Match(maxOldSoHieu);
                            int maxOldID = 0;
                            try
                            {
                                maxOldID = int.Parse(match.Value);
                            }
                            catch
                            {
                            }
                            string digits = (++maxOldID).ToString();
                            int digitsLength = digits.Length;
                            for (int i = digitsLength; i < noDigits; i++)
                            {
                                digits = "0" + digits;
                            }
                            soChungTu = string.Format("{0}{1}", prefix, digits);
                            //while (existed)
                            //{
                            //    soChungTu = string.Format("{0}{1}", suffix, digits);
                            //    cmd = new SqlCommand("SELECT COUNT(*) FROM 
                            //}
                        }
                        else
                        {
                            string digits = "1";
                            int digitsLength = digits.Length;
                            for (int i = digitsLength; i < noDigits; i++)
                            {
                                digits = "0" + digits;
                            }
                            soChungTu = string.Format("{0}{1}", prefix, digits);
                        }
                    }
                    catch (Exception ex)
                    {
                    }
                }
                return soChungTu;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        public static string GetSoHieuMacDinhChoChuongTrinhKhuyenMai(int kieuKhuyenMai, string fieldName, string prefix, int noDigits)
        {
            try
            {
                string soChungTu = "";
                if (fieldName == "") fieldName = "So";
                using (SqlConnection con = new SqlConnection(ConnectString))
                {
                    try
                    {
                        con.Open();

                        string strSql = string.Format("SELECT TOP 1 * FROM ChuongTrinhKhuyenMai WHERE KieuKhuyenMai = {0} ORDER BY Ma DESC", kieuKhuyenMai);
                        SqlCommand cmd = new SqlCommand(strSql, con);
                        SqlDataReader rd = cmd.ExecuteReader();
                        if (rd.Read())
                        {
                            string maxOldSoHieu = (string)rd[fieldName];
                            if (maxOldSoHieu.StartsWith(prefix)) maxOldSoHieu = maxOldSoHieu.Substring(prefix.Length);
                            Regex regex = new Regex(string.Format(@"(?<=.*?)(\d)+", prefix));
                            Match match = regex.Match(maxOldSoHieu);
                            int maxOldID = 0;
                            try
                            {
                                maxOldID = int.Parse(match.Value);
                            }
                            catch
                            {
                            }
                            string digits = (++maxOldID).ToString();
                            int digitsLength = digits.Length;
                            for (int i = digitsLength; i < noDigits; i++)
                            {
                                digits = "0" + digits;
                            }
                            soChungTu = string.Format("{0}{1}", prefix, digits);
                            //while (existed)
                            //{
                            //    soChungTu = string.Format("{0}{1}", suffix, digits);
                            //    cmd = new SqlCommand("SELECT COUNT(*) FROM 
                            //}
                        }
                        else
                        {
                            string digits = "1";
                            int digitsLength = digits.Length;
                            for (int i = digitsLength; i < noDigits; i++)
                            {
                                digits = "0" + digits;
                            }
                            soChungTu = string.Format("{0}{1}", prefix, digits);
                        }
                    }
                    catch (Exception ex)
                    {
                    }
                }
                return soChungTu;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        public static DateTime GetSystemDateTime()
        {
            SqlConnection con = new SqlConnection(ConnectString);
            try
            {
                con.Open();
                SqlCommand cmd = con.CreateCommand();
                return GetSystemDateTime(cmd);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                con.Close();
            }
        }
        public static DateTime GetSystemDateTime(SqlCommand cmd)
        {
            try
            {
                cmd.CommandText = "SELECT GETDATE()";
                DateTime retDate = (DateTime)cmd.ExecuteScalar();
                retDate.Subtract(new TimeSpan(0, 0, 0, 0, retDate.Millisecond));
                return retDate;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        public static DateTime GetThoiDiemKetChuyenGanNhat()
        {
            try
            {
                SqlConnection con = new SqlConnection(ConnectString);
                DateTime retValue = new DateTime(1900, 1, 1);

                con.Open();
                SqlCommand cmd = con.CreateCommand();
                cmd.CommandText = string.Format("SELECT TOP 1 A.Ngay \n" +
                                                "FROM (SELECT TOP 1 Ngay FROM ChungTu WHERE LoaiChungTuID = 302 \n" +
                                                        "UNION \n" +
                                                        "SELECT  TOP 1 ThoiDiem AS Ngay FROM ThoiDiemKhoaSo ) A \n" +
                                                "ORDER BY Ngay DESC");
                SqlDataReader rd = cmd.ExecuteReader();
                if (rd.Read())
                {
                    retValue = (DateTime)rd["Ngay"];
                    rd.Close();
                }
                else
                {
                    retValue = new DateTime(1900, 1, 1, 0, 0, 00);
                }
                return retValue;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        public static DateTime GetThoiDiemKetChuyenGanNhat(DateTime thoiDiem)
        {
            SqlConnection con = new SqlConnection(ConnectString);
            DateTime retValue = new DateTime(1900, 1, 1);
            try
            {
                con.Open();
                SqlCommand cmd = con.CreateCommand();
                cmd.CommandText = string.Format("SELECT TOP 1 A.Ngay \n" +
                                                "FROM (SELECT TOP 1 Ngay FROM ChungTu WHERE Ngay < @ThoiDiem AND LoaiChungTuID = (SELECT ID FROM LoaiChungTu WHERE Ma = N'PhieuKetChuyenTuDong') \n" +
                                                        "UNION \n" +
                                                        "SELECT  TOP 1 ThoiDiem AS Ngay FROM ThoiDiemKhoaSo WHERE ThoiDiem < @ThoiDiem) A \n" +
                                                "ORDER BY Ngay DESC");
                cmd.Parameters.Clear();
                cmd.Parameters.AddWithValue("ThoiDiem", thoiDiem);

                SqlDataReader rd = cmd.ExecuteReader();
                if (rd.Read())
                {
                    retValue = (DateTime)rd["Ngay"];
                    rd.Close();
                }
                else
                {
                    retValue = new DateTime(1900, 1, 1, 0, 0, 00);
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                con.Close();
            }
            return retValue;
        }

        public static DateTime GetSystemTimeOfDate(DateTime specifyDate)
        {
            try
            {
                DateTime systemTime = GetSystemDateTime();
                return new DateTime(specifyDate.Year, specifyDate.Month, specifyDate.Day,
                                           systemTime.Hour, systemTime.Minute, systemTime.Second, systemTime.Millisecond);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        public static string DateTimeVNToString(DateTime dateTime)
        {
            try
            {
                return dateTime.Day.ToString() + "/" + dateTime.Month.ToString() + "/" + dateTime.Year.ToString();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        public static string Double2Money(double money)
        {
            try
            {
                string ret = "";
                bool soAm = false;
                if (money < 0)
                {
                    money = -money;
                    soAm = true;
                }

                double real = Math.Floor(money);
                while (real >= 1000)
                {
                    string tem = ((int)(real % 1000)).ToString();
                    if (tem.Length == 1) tem = "00" + tem;
                    else if (tem.Length == 2) tem = "0" + tem;
                    ret = tem + "." + ret;
                    real = Math.Floor(real / 1000);
                }
                ret = ((int)(real % 1000)).ToString() + "." + ret;
                if (ret.EndsWith(".")) ret = ret.Substring(0, ret.Length - 1);
                if (soAm) ret = "-" + ret;
                return ret;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        public static string Decimal2Money(decimal money)
        {
            try
            {
                string ret = "";
                bool soAm = false;
                if (money < 0)
                {
                    money = -money;
                    soAm = true;
                }

                double real = Math.Floor((double)money);
                while (real >= 1000)
                {
                    string tem = ((int)(real % 1000)).ToString();
                    if (tem.Length == 1) tem = "00" + tem;
                    else if (tem.Length == 2) tem = "0" + tem;
                    ret = tem + "." + ret;
                    real = Math.Floor(real / 1000);
                }
                ret = ((int)(real % 1000)).ToString() + "." + ret;
                if (ret.EndsWith(".")) ret = ret.Substring(0, ret.Length - 1);
                if (soAm) ret = "-" + ret;
                return ret;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        public static DataTable GetDataBySql(string selectSQL)
        {
            SqlConnection con = new System.Data.SqlClient.SqlConnection(ConnectString);
            try
            {
                con.Open();

                SqlCommand cmd = con.CreateCommand();
                SqlDataAdapter da = new System.Data.SqlClient.SqlDataAdapter();
                DataTable dt = new System.Data.DataTable();

                cmd.CommandText = selectSQL;
                da.SelectCommand = cmd;

                da.Fill(dt);
                con.Close();
                return dt;
            }
            catch (System.Exception)
            {
                throw;
            }
            finally
            {
                con.Close();
            }
        }

        //Full option cho grid
        public static void SetGridviewOption(ASPxGridView gridView, string titleGridView, bool showCommandColumn)
        {
            //Các settings quan trọng để AspxGridview chạy hợp lý
            gridView.SettingsPopup.EditForm.AllowResize = true;
            gridView.SettingsBehavior.ConfirmDelete = true;  //Hiện confirmkhi delrte
            gridView.SettingsBehavior.EnableCustomizationWindow = true;
            gridView.SettingsPopup.EditForm.HorizontalAlign = DevExpress.Web.ASPxClasses.PopupHorizontalAlign.WindowCenter;  //Show EditForm giữa màn hình
            gridView.SettingsPopup.EditForm.VerticalAlign = DevExpress.Web.ASPxClasses.PopupVerticalAlign.WindowCenter;  //Show EditForm giữa màn hình
            gridView.SettingsEditing.Mode = GridViewEditingMode.PopupEditForm;  //Sửa form kiểu PopupEditForm
            gridView.SettingsPager.PageSize = CommonLib.PageSize_DoDaiTrang;  //Phân trang
            gridView.SettingsText.ConfirmDelete = "Bạn có chắc chắn muốn xóa?";    //Chuyển text confirm sang tiếng việt
            gridView.SettingsText.GroupPanel = "Kéo cột cần nhóm vào đây";  //Việt hóa group panel nhóm (nếu nó đc hiển thị)

            //Hiện title của grid
            gridView.Settings.ShowTitlePanel = true;
            gridView.SettingsText.Title = titleGridView.ToUpper();

            //Nếu option có show nút thêm sửa xóa
            if (showCommandColumn)
            {
                bool isExistedCommandColumn = false;
                foreach (var column in gridView.Columns)  //Tìm kiếm trên grid theo disply text
                {
                    //Xóa nút thêm sửa xóa nếu có,nhưng vẫn setting cho Update,Cancel vì có thể nó vẫn hiện trong editform
                    if (column is GridViewCommandColumn)
                        isExistedCommandColumn = true;
                }

                if (!isExistedCommandColumn)
                {
                    GridViewCommandColumn commandColumn = new GridViewCommandColumn("Thao tác");

                    commandColumn.NewButton.Visible = true;
                    commandColumn.EditButton.Visible = true;
                    commandColumn.DeleteButton.Visible = true;
                    commandColumn.VisibleIndex = 0;

                    gridView.Columns.Add(commandColumn);
                }
            }

            foreach (var column in gridView.Columns)  //Tìm kiếm trên grid theo disply text
            {
                //Xóa nút thêm sửa xóa nếu có,nhưng vẫn setting cho Update,Cancel vì có thể nó vẫn hiện trong editform
                if (column is GridViewCommandColumn)
                {
                    if (showCommandColumn == false)
                    {
                        (column as GridViewCommandColumn).NewButton.Visible = false;
                        (column as GridViewCommandColumn).EditButton.Visible = false;
                        (column as GridViewCommandColumn).DeleteButton.Visible = false;
                    }

                    (column as GridViewCommandColumn).ButtonType = System.Web.UI.WebControls.ButtonType.Image;

                    (column as GridViewCommandColumn).NewButton.Text = "Thêm";
                    (column as GridViewCommandColumn).NewButton.Image.Url = "/Icons/Sigma/Add_16x16_Gray.png"; // = "Thêm";
                    (column as GridViewCommandColumn).EditButton.Text = "Sửa";
                    (column as GridViewCommandColumn).EditButton.Image.Url = "/Icons/Sigma/Edit_16x16_Gray.png"; // = "Sửa";
                    (column as GridViewCommandColumn).DeleteButton.Text = "Xóa";
                    (column as GridViewCommandColumn).DeleteButton.Image.Url = "/Icons/Sigma/Delete_16X16_Gray.png"; // = "Xóa";

                    (column as GridViewCommandColumn).UpdateButton.Text = "Cập nhật";
                    (column as GridViewCommandColumn).UpdateButton.Image.Url = "/images/save.png"; // = "Lưu";

                    (column as GridViewCommandColumn).CancelButton.Text = "Hủy bỏ";
                    (column as GridViewCommandColumn).CancelButton.Image.Url = "/images/cancel.png"; // = "Hủy bỏ";

                    (column as GridViewCommandColumn).Width = 70;
                }

                #region set filter theo displaytext
                if (column is GridViewDataColumn)
                {
                    (column as GridViewDataColumn).Settings.FilterMode = ColumnFilterMode.DisplayText;
                    (column as GridViewDataColumn).Settings.AutoFilterCondition = AutoFilterCondition.Contains;

                    try
                    {
                        if (column != null)
                        {
                            object value = gridView.GetRowValues(0, (column as GridViewDataColumn).FieldName);
                            if (value is DateTime)
                            {
                                //Không hiểu sao NgaySinh lại nhảy vào đây nên try catch, để thế này lại chạy được
                                (column as GridViewDataDateColumn).PropertiesDateEdit.DisplayFormatString = "dd/MM/yyyy";
                                (column as GridViewDataDateColumn).PropertiesEdit.DisplayFormatString = "dd/MM/yyyy";
                                //Cho EditForm
                                (column as GridViewDataDateColumn).PropertiesDateEdit.EditFormatString = "dd/MM/yyyy";
                            }
                            else if (value is decimal)
                            {
                                (column as GridViewDataTextColumn).PropertiesEdit.DisplayFormatString = CommonLib.NumbericFormatString;
                                (column as GridViewDataTextColumn).PropertiesTextEdit.DisplayFormatString = CommonLib.NumbericFormatString;
                                (column as GridViewDataTextColumn).PropertiesTextEdit.DisplayFormatInEditMode = true;
                                //Hiện khi click chuột vào để sửa dữ liệu. Hiển thị kiểu 100000.0, nếu k thích có dấu .0 đằng sau thì bỏ <0..9g> đi
                                //Tốt nhất nên dùng kiểu bigint (trong sql) và int64 trên C# nếu k cần dấu chấm động đăng sau
                                //(column as GridViewDataTextColumn).PropertiesTextEdit.MaskSettings.Mask = "<0..999999999999g>.<0..9g>"; //Lỗi khi đặt ở đây, nhưng đặt trực tiếp ở form thì được
                            }
                            else if (value is int || value is Int16 || value is Int32 || value is Int64)
                            {
                                //1 số nhóm là ID reference từ các bảng khác thì k cần set, nên để trong try catch, lỗi thì thôi
                                (column as GridViewDataTextColumn).PropertiesEdit.DisplayFormatString = CommonLib.IntegerFormatString;
                                (column as GridViewDataTextColumn).PropertiesTextEdit.DisplayFormatString = CommonLib.IntegerFormatString;
                                (column as GridViewDataTextColumn).PropertiesTextEdit.DisplayFormatInEditMode = true;
                            }
                        }
                    }
                    catch (System.Exception ex)
                    { }
                }
                else if (column is GridViewDataTextColumn)
                {
                    (column as GridViewDataTextColumn).Settings.FilterMode = ColumnFilterMode.DisplayText;
                    (column as GridViewDataTextColumn).Settings.AutoFilterCondition = AutoFilterCondition.Contains;
                }
                else if (column is GridViewDataComboBoxColumn)
                {
                    (column as GridViewDataComboBoxColumn).Settings.FilterMode = ColumnFilterMode.DisplayText;
                    (column as GridViewDataComboBoxColumn).Settings.AutoFilterCondition = AutoFilterCondition.Contains;
                    (column as GridViewDataComboBoxColumn).PropertiesEdit.NullDisplayText = "";
                }
                else if (column is GridViewDataDateColumn)
                {
                    (column as GridViewDataDateColumn).Settings.FilterMode = ColumnFilterMode.DisplayText;
                    (column as GridViewDataDateColumn).Settings.AutoFilterCondition = AutoFilterCondition.Contains;
                    (column as GridViewDataDateColumn).PropertiesDateEdit.DisplayFormatString = "dd/MM/yyyy";
                    (column as GridViewDataDateColumn).PropertiesEdit.DisplayFormatString = "dd/MM/yyyy";
                    //Cho EditForm
                    (column as GridViewDataDateColumn).PropertiesDateEdit.EditFormatString = "dd/MM/yyyy";
                }
                else if (column is GridViewDataDropDownEditColumn)
                {
                    (column as GridViewDataDropDownEditColumn).Settings.FilterMode = ColumnFilterMode.DisplayText;
                    (column as GridViewDataDropDownEditColumn).Settings.AutoFilterCondition = AutoFilterCondition.Contains;
                }
                else if (column is GridViewDataImageColumn)
                {
                    (column as GridViewDataImageColumn).Settings.FilterMode = ColumnFilterMode.DisplayText;
                    (column as GridViewDataImageColumn).Settings.AutoFilterCondition = AutoFilterCondition.Contains;
                }
                else if (column is GridViewDataMemoColumn)
                {
                    (column as GridViewDataMemoColumn).Settings.FilterMode = ColumnFilterMode.DisplayText;
                    (column as GridViewDataMemoColumn).Settings.AutoFilterCondition = AutoFilterCondition.Contains;
                }
                else if (column is GridViewDataSpinEditColumn)
                {
                    (column as GridViewDataSpinEditColumn).Settings.FilterMode = ColumnFilterMode.DisplayText;
                    (column as GridViewDataSpinEditColumn).Settings.AutoFilterCondition = AutoFilterCondition.Contains;
                }
                else if (column is GridViewDataTimeEditColumn)
                {
                    (column as GridViewDataTimeEditColumn).Settings.FilterMode = ColumnFilterMode.DisplayText;
                    (column as GridViewDataTimeEditColumn).Settings.AutoFilterCondition = AutoFilterCondition.Contains;
                }
                #endregion
            }
        }

        //Xuất excel
        public static void ExportExcelAspxGridView(DevExpress.Web.ASPxGridView.Export.ASPxGridViewExporter gridExporter, string fileName)
        {
            //gridExporter.ExportedRowType = DevExpress.Web.ASPxGridView.Export.GridViewExportedRowType.Selected;
            gridExporter.WriteXlsxToResponse(fileName);
        }

        //Copy convert số của a Nam sang cho tiện dùng
        public static int? convertIntOrNull(string text)
        {
            int? res = null;
            try
            {
                res = Convert.ToInt32(text);
            }
            catch
            {
            }
            return res;
        }
        public static string showNgayTuoi(string ngay)
        {

            string res = "";
            DateTime ngaymuon = Convert.ToDateTime(ngay);
            DateTime ngaytra = DateTime.Now;
            TimeSpan Time = ngaymuon - ngaytra;
            int TongSoNgay = Time.Days;


            if (ngaymuon.Year <= 1900)
                res = "";
            else
                res = Math.Abs(TongSoNgay).ToString();
            return res;

        }
        public static float convertFloat(string text)
        {
            float res = 0;
            try
            {
                float.TryParse(text, out res);
            }
            catch
            {
                res = 0;
            }
            return res;
        }
        public static DateTime convertNgay(string ngaybatdau)
        {
            try
            {
                string[] dtemp = ngaybatdau.Split('/');
                if (dtemp.Length > 2)
                {
                    return DateTime.ParseExact(ngaybatdau, "d/M/yyyy", CultureInfo.InvariantCulture);
                }
            }
            catch
            {
                return DateTime.Parse("01/01/1900");
            }
            return DateTime.Parse("01/01/1900");
        }
        public static int convertInt(string text)
        {
            int res = 0;
            try
            {
                int.TryParse(text, out res);
            }
            catch
            {
                res = 0;
            }
            return res;
        }

        public static Stream StringToStream(string str)
        {
            MemoryStream stream = new MemoryStream();
            StreamWriter writer = new StreamWriter(stream);
            writer.Write(str);
            writer.Flush();
            stream.Position = 0;
            return stream;
        }
    }

    //Class dùng để lookup dữ liệu
    public class LookupTemplate : ITemplate
    {
        public string LookID { get; set; }  //ID của lookup, để lấy dữ liệu trong Event Updating, Inserting
        public DataTable Source { get; set; }
        public string FieldName { get; set; }  //Cột ID để check vào lookup
        public int DisplayFieldIndex { get; set; } //Cột display lên màn hình, thường là mã hoặc tên
        public bool ReadOnly { get; set; } //Cột display lên màn hình, thường là mã hoặc tên

        public void InstantiateIn(Control container)
        {
            ASPxGridLookup lookup = new ASPxGridLookup { ID = LookID };

            lookup.KeyFieldName = FieldName;
            lookup.IncrementalFilteringMode = IncrementalFilteringMode.Contains;

            lookup.TextFormatString = "{" + DisplayFieldIndex + "}";
            lookup.DataSource = Source;

            lookup.GridView.Styles.AlternatingRow.Enabled = DevExpress.Utils.DefaultBoolean.True;
            lookup.GridView.SettingsBehavior.AllowFocusedRow = true;
            lookup.GridView.SettingsBehavior.EnableRowHotTrack = true;

            //Set số lượng row trên 1 trang, trong phân trang của popup
            lookup.GridView.SettingsPager.PageSize = 1000;

            //Set độ rộng của popup
            lookup.GridView.Width = Unit.Pixel(250);

            lookup.ReadOnly = ReadOnly;

            lookup.Load += lookup_Load;
            container.Controls.Add(lookup);
            lookup.DataBind();

            //Ẩn cột FieldName (thường là ID) đi vì hiện ra nhìn rối, k cần thiết
            //Đặt sau DataBind để tên cột đã xuất hiện, k là bị lỗi null
            try
            {
                lookup.Columns[FieldName].Visible = false;
            }
            catch (System.Exception ex)
            { }
        }

        void lookup_Load(object sender, EventArgs e)
        {
            ASPxGridLookup lkp = (ASPxGridLookup)sender;
            GridViewDataItemTemplateContainer cont = (GridViewDataItemTemplateContainer)lkp.NamingContainer;
            lkp.Value = DataBinder.Eval(cont.DataItem, FieldName);
        }
    }

    public enum EditState
    {
        None,
        CreatingNew,
        Modifying,
        Saved,
    }
}